﻿using MediatR;
using Newtonsoft.Json;
using S.Archives.Domain.S.ArchivesDto;
using S.EliminationOrDath.Domain.ApiResult;
using S.EliminationOrDath.Domain.APIResult;
using S.EliminationOrDath.Domain.Enums;
using S.EliminationOrDath.Infrastructure.Interface;
using S.EliminationOrDath.Read.API.Application.Command.SheepDeathCommand;


namespace S.EliminationOrDath.Read.API.Application.CommandHandlers.SheepDeathCommandHandler
{
    /// <summary>
    /// 羊只死亡
    /// </summary>
    public class SheepDeathListPageCommandHandler : IRequestHandler<SheepDeathListPageCommand, ApiResult<List<DeathDto>>>
    {
        private readonly ISheepDeathRepository _sheepDeathRepository;
        private readonly IConfiguration _configuration;
        public SheepDeathListPageCommandHandler(ISheepDeathRepository sheepDeathRepository, IConfiguration configuration)
        {
            _sheepDeathRepository= sheepDeathRepository;
            _configuration= configuration;
        }
        /// <summary>
        /// 羊只死亡查询显示+分页
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<DeathDto>>> Handle(SheepDeathListPageCommand request, CancellationToken cancellationToken)
        {
            var query = await _sheepDeathRepository.GetAll();

            var i = _configuration["WebApiIp"];

            //构造HTTP请求
            HttpClient httpClient = new HttpClient();
            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, $"{i}/ach/api/SheepFileModel/GetSheepFilesAll?id=0");
            HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest);

            //读取响应内容
            string responseContent = await httpResponse.Content.ReadAsStringAsync();

            //反序列化响应内容为 SheepFleModel 的列表
            List<SheepFileDto> sheepFiles =JsonConvert.DeserializeObject<List<SheepFileDto>>(responseContent);

            //使用LINQ 进行连接查询
            var list = from a in query.AsEnumerable()
                       join b in sheepFiles on a.EarTag equals b.EarTag
                       where (string.IsNullOrEmpty(request.Sdate) || a.DeathDate >= DateTime.Parse(request.Sdate)) &&
                             (string.IsNullOrEmpty(request.edate) || a.DeathDate < DateTime.Parse(request.edate).AddDays(1)) &&
                             (string.IsNullOrEmpty(request.EarTag) || a.EarTag.Contains(request.EarTag)) &&
                             (request.DId == 0 || a.DeathType == (DeathType)request.DId)
                       select new DeathDto
                       {
                           reproductiveState=(int)b.ReproductiveState,
                           birthDate =b.BirthDate,
                           DeathId =a.DeathId,
                           DeathDate = a.DeathDate,
                           SheepType = a.SheepType,
                           DocumentNumber = a.DocumentNumber,
                           EarTag = a.EarTag,
                           DeathType = a.DeathType,
                           VarietyEnum = a.VarietyEnum,
                           DeathSex = a.DeathSex,
                           BuildingName = a.BuildingName,
                           ColumnName = a.ColumnName,
                           Remark = a.Remark,
                           Auditor = a.Auditor,
                           AuditorTime = a.AuditorTime,
                           CreateBy = a.CreateBy,
                           CreateDate = a.CreateDate,
                           UpdateBy = a.UpdateBy,
                           UpdateDate = a.UpdateDate,
                       };
            var death=list.ToList();

            ApiResult<List<DeathDto>>  apideath=new ApiResult<List<DeathDto>>();
            apideath.Data = death;
            //总条数、总页数
            apideath.totalCount = death.Count();
            apideath.pageCount = (int)Math.Ceiling((apideath.totalCount * 1.0) / request.pageSize);
            //分页
            apideath.Data = death.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            return apideath;
        }
    }
}
